package com.itedge.solutionmanager.service.domain.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import com.itedge.infrastructure.service.domain.impl.AbstractJpaProcessEntityService;
import com.itedge.solutionmanager.domain.impl.Customer;
import com.itedge.solutionmanager.service.domain.ICustomerService;

@Service
public class CustomerService extends AbstractJpaProcessEntityService<Customer> 
	implements ICustomerService  {
	
	@PersistenceContext
    transient EntityManager entityManager;

	@Override
	protected EntityManager getEntityManager() {
		return this.entityManager;
	}

	@Override
	protected Class<Customer> getClassReference() {
		return Customer.class;
	}	
	
	@Override
	public List<Customer> findEntitiesByEnumeration(Enum<?> param) {
        return this.entityManager.createQuery("select o from Customer o where o.status = :activeStatus", 
        		Customer.class).setParameter("activeStatus", param).getResultList();
    }
	
	//TODO: rewrite to use CriteriaQuery
	@Override
	public List<Customer> findEntitiesByCriteria(Customer searchCustomer, Integer maxResults) {	
		List<Customer> result  = null;
		try {
			TypedQuery<Customer> query = 
				this.entityManager.createQuery("select o from Customer o where upper(o.name) like upper(:searchName)",
						Customer.class).setParameter("searchName", '%'+searchCustomer.getName()+'%');
			if (maxResults != null) {
				query.setMaxResults(maxResults);
			}
			result = query.getResultList();
		} catch(EmptyResultDataAccessException e){
        	return null;
        } catch(NoResultException e) {
	        return null;
	    }
		return result;
	}	
	
}